package com.meng.jwt.handle;

import com.meng.jwt.Dto.UserTokenDTO;
import com.meng.jwt.utils.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xinqimeng
 * @version 1.0.0
 * @ClassName AuthenticateInterceptor.java
 * @Description TODO
 * @createTime 2022年10月26日 16:30:00
 */
public class AuthenticateInterceptor implements HandlerInterceptor {

    @Resource
    private JedisPool jedisPool;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        //放行login请求
        if (request.getRequestURI().contains("login")) {
            return true;
        }
        String authToken = request.getHeader("Authorization");
//        String token = authToken.substring("Bearer".length() + 1).trim();
        UserTokenDTO userTokenDTO = JWTUtil.parseToken(authToken);
        //1.判断请求是否有效
        if (jedisPool.getResource().get(userTokenDTO.getId()) == null
                || !jedisPool.getResource().get(userTokenDTO.getId()).equals(authToken)) {
            return false;
        }

        //2.判断是否需要续期
//        if (redisService.getExpireTime(userTokenDTO.getId()) < 1 * 60 * 30) {
//            redisService.set(userTokenDTO.getId(), token);
//            log.error("update token info, id is:{}, user info is:{}", userTokenDTO.getId(), token);
//        }
        return true;
    }
}
